﻿using System;
using System.Collections.Generic;
using System.Xml;
using TestsBase.lib;

namespace TestsBase.DB
{
    public class XMLLoader
    {
        private string _fileName;
        private XmlDocument xml;

        public XMLLoader(string fileName)
        {
            _fileName = fileName;
            try
            {
                xml = new XmlDocument();
                xml.Load(fileName);
            }
            catch
            {
                throw new Exception(string.Format("Cant open XML file '{0}'", fileName));
            }
        }

        private static int ListIndexOf(XmlNodeList List, string Name)
        {
            int res = 0;
            foreach (XmlNode node in List)
            {
                if (node.Name == Name) return res;
                res++;
            }
            return -1;
        }

        private static List<string> GetChildList(XmlNode node)
        {
            List<string> res = new List<string>();
            XmlNodeList list = node.ChildNodes;
            foreach (XmlNode items in list)
            {
                res.Add(items.InnerText);
            }
            return res;
        }


        public TestDatabase Fetch()
        {
            if (null == xml) throw new Exception("Not inicialized");
            string quizName = xml.DocumentElement.Attributes["name"].Value.ToString();
            XmlNodeList tests = xml.DocumentElement.ChildNodes;
            TestDatabase newQuiz = new TestDatabase(quizName, tests.Count);

            foreach (XmlNode xmlTest in tests)
            {
                string testName = xmlTest.Attributes["name"].Value.ToString();
                string testTypeString = xmlTest.Attributes["type"].Value.ToString();
                TestType testType;
                switch (testTypeString)
                {
                    case "checkbox":
                        testType = TestType.CheckBox;
                        break;
                    case "radio":
                        testType = TestType.RadioBtn;
                        break;
                    default:
                        testType = TestType.Regex;
                        break;
                }

                Test newTest = new Test(testType, testName);
                XmlNodeList testParams = xmlTest.ChildNodes;

                newTest.Question = testParams[ListIndexOf(testParams, "question")].InnerText;
                //newTest.Value = testParams[IndexOf(testParams, "value")].InnerText;
                List<string> answers = GetChildList(testParams[ListIndexOf(testParams, "answers")]);
                List<string> correct = GetChildList(testParams[ListIndexOf(testParams, "correct")]);
                newTest.LoadAnswers(answers, correct);

                newQuiz.Tests.Add(newTest);
            }
            return newQuiz;
        }
    }
}